<template>
      <!-- 弹框：二级数据 -->
      <el-dialog class="dialogVisible" :title="localParam.name" 
      :visible.sync="dialogVisible" 
      width="90%" :show-close="true" 
      :close-on-press-escape=false 
      :close-on-click-modal=false 
      :destroy-on-close=true
      :before-close="closeBefore"
      :modal-append-to-body="false">
         <div class="content-table">
               <div class="dialogVisibleForm">
                  <div>请在下方完善信息详情：</div>
                  <div v-show="total>0 && isAllowEdit" class="functionButton">
                     <!-- <el-button v-show="parseInt(groupObj.attr1) == -1 || (allFieldList[mIndex].groupList[gIndex].section.length < parseInt(groupObj.attr1))" type="primary" size="mini" @click="addGroup(mIndex,gIndex)">新增</el-button> -->
                     <el-button v-show="editSectionIndex !== -1?false:true && dataList.length < maxDataCount" type="primary" @click="add()" size="mini">新增</el-button>
                     <!-- <el-tooltip  v-show="editSectionIndex.length>0?true:false" class="item" effect="dark" content="请先保存正在编辑的信息" placement="top">
                        <span><el-button type="primary" disabled=true size="mini">新增</el-button></span>
                     </el-tooltip> -->
<!--                        <div>-->
<!--                            <el-button type="primary" size="mini" @click="$event.currentTarget.nextSibling.click();">导入表格</el-button>-->
<!--                            <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @change="currentGroup={id:dialogVisible_1_data[0][0].groupId,name:dialogVisible_1_title};importData($event)" style="display:none;">-->
<!--                        </div>-->
                     <el-button type="primary" @click="exportData(dataList[0][0].groupId,localParam.name)" size="mini">导出</el-button>
                  </div>
               </div>
            
               <el-table :data="dataList" border size="mini" style="width: 100%" header-row-class-name="table-header">

                  <el-table-column prop="headObj.userSelection" :label="headObj.name" v-for="(headObj,headIndex) in dataModel" :key="headIndex" align="center">
                        <template slot-scope="scope">
                           <div v-show="scope.row[headIndex].isShow" class="formItem" :class="[{unsaved:unsavedParamIdList.indexOf(findParamKey(scope.row[headIndex])) != -1}]">
                              <span v-show="editSectionIndex !== scope.$index || editSectionIndex === -1?true:false">

                                 <div v-if="scope.row[headIndex].type == 'file' || scope.row[headIndex].type == 'img'" class="value">
                                    <a :href="fileDownloadUrl + scope.row[headIndex].userSelection.parameterValue">
                                          {{scope.row[headIndex].userSelection.parameterValue.split('/')[scope.row[headIndex].userSelection.parameterValue.split('/').length-1]}}
                                    </a>
                                 </div>
                                 <div v-else>
                                    {{scope.row[headIndex].userSelection.parameterValue}}
                                 </div>
                              </span>
                              <basic-info-form-value v-show="editSectionIndex === scope.$index?true:false" 
                              :paramObj="scope.row[headIndex]"
                              @paramValueChange="paramValueChange"
                              @deleteAttachment="deleteAttachment"
                              ></basic-info-form-value>
                           </div>
                     </template>
                  </el-table-column>
                  <el-table-column v-if="isAllowEdit" width="160px" align="center">
                     <template slot-scope="scope">
                        <div class="operation">
                           <el-button v-show="editSectionIndex === -1?true:false" type="primary" size="mini" plain  @click="edit(scope.$index)">编辑</el-button>
                           <el-button v-show="editSectionIndex === scope.$index?true:false" type="primary" size="mini" plain @click="save(scope.row,scope.$index)">保存</el-button>
                           <el-button v-show="editSectionIndex === scope.$index || editSectionIndex === -1?true:false" type="danger" size="mini" plain @click="deleteRow(scope.row,scope.$index)">删除</el-button>
                        </div>
                     </template>
                  </el-table-column>

               </el-table>

               <!-- 开始填写提醒 -->
               <div v-show="total<=0 && editSectionIndex=== -1" class="editPrompt">
                  <el-button v-show="isAllowEdit===true && isLoadingData === false" type="primary" size="mini" round plain @click="edit(0)" style="margin-left: 10px;">
                     <i class="el-icon-edit"></i>&nbsp;开始录入
                  </el-button>
                  <div style="color:gray;" v-show="isAllowEdit===false && isLoadingData === false">无数据</div>
                  
                  <div  v-show="isLoadingData === true">正在加载...</div>
                  
               </div>

                <el-pagination
                  v-show="totalPages > 1 && editSectionIndex===-1"
                  background
                  layout="total, prev, pager, next"
                  @current-change="loadData()"
                  :current-page.sync="currentPage"
                  :page-size="pageSize"
                  :total="total">
               </el-pagination>

               <!-- <span slot="footer" class="dialogVisibleFooter dialog-footer">
                  <el-button @click="dialogVisible = false" size="mini">关 闭</el-button>
                  <el-button type="primary" @click="dataList(dataList[0][0].groupId)" size="mini">保 存</el-button>
               </span> -->

               
         </div>

         
         <!-- 弹框：文件上传提示 -->
         <div ref="fileUploadLoading" class="fileUploadLoading">
               <div class="content">
                  <i class="el-icon-loading"></i> 正在上传...
               </div>
         </div>

      </el-dialog>
</template>

<script>

import { processingGroupData,getParamKey,processingParamValueChange,exportData,processingAssociatedFields,deleteSection,save } from '../service/personalInfoDataProcessing'

export default {
    props:{
      param:{
         type:Object,     // 属性值类型必须是Object；可选的类型有：String、Number、Object、Array等
         required:false,  // 此属性值为必填; 使用当前组件时，若未传入此值就会报错
      },
      userId:{ // 用户ID
         type: String,
         required:false,
         default:""
      }
   },
   data(){
      return {
         isAllowEdit:true,        // 是否允许编辑
         localParam:{},
         paramValueMap:new Map(), // 原始值
         editSectionIndex:-1,     // 正在编辑的参数行索引


         // 组数据
         dialogVisible:false,
         dataList:[],
         dataModel:[],
         maxDataCount:10000,
         isLoadingData:true, // 是否正在加载数据

         unsavedParamIdList:[],

         currentPage: 1,
         pageSize: 5,
         total:0,       // 总数
         totalPages:0,  // 总页数

         currentAddSectionIndex:-1, // 当前正在添加的seciont索引

         fileDownloadUrl:''
      }
   },
   created() {
      this.fileDownloadUrl = '/admin/qaStandardRecord/download?targetUrl=';
   },
   methods:{
      // 显示二级弹框
      show(param,isAllowEdit){
         
         this.isAllowEdit = isAllowEdit;

         this.localParam = param;
         this.dialogVisible = true;
         this.loadData(this.localParam);
      },
      // 保存section
      save(paramList,index){

         let groupId = this.dataList[0][0].groupId;

         var that = this;
         save([paramList],groupId,this,(isSuccess,res)=>{
            if(isSuccess){
               // 刷新当前数据页面
               that.loadData(that.localParam);
               that.editSectionIndex = -1;

               // 触发一级表为编辑模式，以便更新一级表的参数字段（必须让用户自己手动执行保存，因为旧数据可能无法通过新的正则验证规则）
               // 此处通过发送消息来告知一级表，因为这里与一级的组件层级过多，无法直接告知一级表
               window.postMessage({
                  source:"review-base-info-secondary-save-callback", // 消息来源
                  data:res.data.parentValue
               }, "*");

            }
         });
      },
      // 编辑seciton
      edit(index){
         this.editSectionIndex = index;
      },
      // 删除section
      deleteRow(paramList,index){

         var that = this;
         that.editSectionIndex = -1;
         deleteSection(paramList,this,(isSuccess,res)=>{
            if(isSuccess){
               // 刷新当前数据页面
               that.currentPage = 1;
               that.loadData(that.localParam);

               // 触发一级表为编辑模式，以便更新一级表的参数字段（必须让用户自己手动执行保存，因为旧数据可能无法通过新的正则验证规则）
               // 此处通过发送消息来告知一级表，因为这里与一级的组件层级过多，无法直接告知一级表
               window.postMessage({
                  source:"review-base-info-secondary-save-callback", // 消息来源
                  data:res.data.parentValue
               }, "*");
            }
         });
      },
      // 添加section
      add(){
         let paramList = JSON.parse(JSON.stringify(this.dataModel));
         paramList.forEach((param)=>{
            // param.maxOrder = param.maxOrder;
            param.userSelection.parameterValue = "";
            param.userSelection.startDate = "";
            param.userSelection.endDate = "";
            param.userSelection.orders = parseInt(param.maxOrder) + 1;
         });
         this.dataList.push(paramList);
         this.editSectionIndex = this.dataList.length-1;
      },
      // 删除附件
      deleteAttachment(param){
         var key = getParamKey(param);
         this.unsavedParamIdList.remove(key);
         processingAssociatedFields(param,this.dataList[this.editSectionIndex]);
      },
      // 监听参数值变化
      paramValueChange(event,param,type1){
         processingParamValueChange(event,param,type1,this.dataList[this.editSectionIndex],this)
      },
      // 加载数据
      loadData(){
         
         let that = this;

         that.isLoadingData = true;

         var formData = new FormData;
         formData.append("pageNum",this.currentPage);
         formData.append("pageSize",this.pageSize);
         formData.append("groupId",this.localParam.id);
         formData.append("type",'2');  // '1' 一级表,  ’2’ 二级表
         formData.append("userId", this.userId);

         this.$api.baseInfoGroupDataPost(formData).then(res => {
               console.time("loadTime");
               if(res.code == 200){

                  // 重置编辑状态
                  this.editSectionIndex = -1;

                  var that = this;
                  var result = processingGroupData(res.data.resultPage.content);
                  this.dataList = [];
                  this.dataList = result.allFieldList; // 所有数据字段
                  this.dataModel = JSON.parse(JSON.stringify(result.allFieldList[0]));

                  this.dataList.forEach((paramList)=>{
                     paramList.forEach((param)=>{
                        param.isEdit = false;
                     });
                  });


                  this.total = res.data.resultPage.total;
                  this.totalPages = res.data.resultPage.totalPages;
               }
               // 加载职称分类option数据列表
               // this.findQaCategories();
               console.timeEnd("loadTime");
          }).finally(function () {  
            that.isLoadingData = false;
         });
      },
      // 导出数据
      exportData(groupId,groupName){
         exportData(groupId,groupName,this);
      },
      // 关闭弹框前提示
      closeBefore(done){

         if(this.editSectionIndex === -1){
            done();
            return;
         }

         this.$confirm('您有信息尚未保存，确定要继续关闭吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '再考虑一下',
            type: 'warning'
         }).then(() => {
               done();
         }).catch(() => {
            
         });
      },
      // 公共 - 获取参数key
      findParamKey(param){
         return getParamKey(param);
      }
   },
   watch:{
      dialogVisible(){
         if(this.dialogVisible === false){
            // 重置编辑状态
            this.editSectionIndex = -1;
         }
      },
      editSectionIndex(){
         if(this.editSectionIndex !== -1){
            let that = this;
            
            that.unsavedParamIdList = [];
            that.paramValueMap.clear();

            this.dataList[this.editSectionIndex].forEach((param)=>{
               that.paramValueMap.set(getParamKey(param),param.userSelection.parameterValue);
            });

         }
      }
   }
}
</script>

<style scoped>

.content-table{
   position: relative;
}


/* 顶部操作 */
.dialogVisibleForm{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}
/* 顶部操作 - 按钮 */
.dialogVisibleForm .functionButton{
    display: flex;
}
.dialogVisibleForm .functionButton>*{
    margin-left: 10px;
}

/* table */
.dialogVisible,.dialogVisible >>> table{
    font-size: 14px;
}
.dialogVisible,.dialogVisible >>> table td>.cell>*{
    width: 100%;
}
.dialogVisible,.dialogVisible >>> table td>.cell button{
    margin: 0px 5px;
}
.dialogVisible .value.file>.fileContent>.close{
    /* margin-right: 16px; */
}


/* 表单项 */
>>> .formItem.unsaved input,
>>> .formItem.unsaved textarea,
>>> .formItem.unsaved select{
    border: red solid 1px;
}
>>> .formItem{
    width: 33%;
    display: flex;
    flex-direction: row;
    align-items: center;
    color:#333333;
    font-size:14px;
    margin:6px 0px;
}
.formItem{
    display: flex;
    align-items: center;
}
.formItem>*{
    width:100%;
}

/* footer */
.dialogVisibleFooter{
    display: flex;
    justify-content:center;
    margin-top: 28px;
}




/* 文件上传Loading */
.fileUploadLoading{
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.12941176470588237);
    z-index: 10000;
    /* display: flex; */
    display: none;
    align-items: center;
    justify-content: center;
}
.fileUploadLoading>.content{
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
    padding: 30px 40px;
    border-radius: 6px;
    font-size: 16px;
}
.fileUploadLoading>.content>i{
    font-size: 20px;
    margin-right: 8px;
}


/* 分页 */
.el-pagination{
   display: flex;
   justify-content: flex-end;
   padding-top: 20px;
   padding-right: 0px;
}


/* 编辑提示 */
.editPrompt{
   display: flex;
   align-items: center;
   justify-content: center;
   background-color: white;
   position:absolute;
   top: 31px;
   bottom: 0px;
   left: 1px;
   right: 1px;
}
   

</style>